<script setup>
import {onMounted, ref} from 'vue';
import luckysheet from "luckysheet";
import LuckyExcel from 'luckyexcel'
import AnalyesAPI from "@/api/system/analyes.ts";
import {useAnalysetStore} from "@/store/index.ts";
import {getUserInfo} from "@/utils/auth.ts";
import {
  filterParallelSamples,
  filterValidSampleAdatas,
  filterValidSamples,
  processData, processTableData,
  splitDataIntoPages,
  transformData
} from "@/utils/method";
import indexPdf from '@/components/analysisSheetComponents/waterCapacity/tmpl48/indexPdf.vue'
import Index from "@/components/analysisSheetComponents/component/index.vue";
import CommonAPI from "@/api/common/index";

const waterForm = ref({
  sampling_time: "", // 采样日期
  pxycd: [
    {px_pxybh: '', px_cdz: '', px_pjz: '', px_xd: '', px_zkyq: '', px_sfhg: ''},
    {px_pxybh: '', px_cdz: '', px_pjz: '', px_xd: '', px_zkyq: '', px_sfhg: ''},
    {px_pxybh: '', px_cdz: '', px_pjz: '', px_xd: '', px_zkyq: '', px_sfhg: ''},
    {px_pxybh: '', px_cdz: '', px_pjz: '', px_xd: '', px_zkyq: '', px_sfhg: ''},
  ],
  unit: {},
  hz_device: {
    hz_device_name: [],
    hz_device_model: [],
    hz_device_number: [],
  },
  tp_device: {
    tp_device_name: [],
    tp_device_model: [],
    tp_device_number: [],
  },
})
const analyseStatusPage = useAnalysetStore()
const record_sn = analyseStatusPage.waterForm.record_sn
const processedData = ref([])
const cdatas = ref([])
const checkDialogVisible = ref(false)
const checkTime = ref('')
const userInfo = JSON.parse(getUserInfo())
const showTargetPage = ref(false)
const tableHeaders = ref([])
const tabler = ref([])
const selectedUsers = ref([])
const drawer2 = ref(false)
const assignedDialogVisible = ref(false)
const spDialogVisible = ref(false)
let ypbhOptions = ref([]) // 编辑人员

const switchAdd = ref(true) //传给组件的
const addSampleForm = ref({
  device_name: [],
})
const addTpSampleForm = ref({
  device_name: [],
})

let options = {
  container: "luckysheet", //luckysheet为容器id
  lang: 'zh',
  autoCalculate: true,
  data: [
    {
      "column": 9,
      "defaultRowHeight": 40, // 自定义行高
      "defaultColWidth": 100, // 自定义列宽
      "celldata": [
        {"r": 0, "c": 0, "v": "样品编号",},
        {"r": 0, "c": 1, "v": "类型",},
        {"r": 0, "c": 2, "v": "取样体积V(mL)",},
        {"r": 0, "c": 3, "v": "初重B(g)",},
        {"r": 1, "c": 3, "v": "初重1",},
        {"r": 1, "c": 4, "v": "初重2",},
        {"r": 1, "c": 5, "v": "初重3",},
        {"r": 0, "c": 6, "v": "初重A(g)",},
        {"r": 1, "c": 6, "v": "终重1",},
        {"r": 1, "c": 7, "v": "终重2",},
        {"r": 1, "c": 8, "v": "终重3",},
        {"r": 0, "c": 9, "v": "样品净重m(g)",},
        {"r": 0, "c": 10, "v": "样品浓度C(mg/L)",},
        {"r": 0, "c": 11, "v": "测定结果",},
        {"r": 0, "c": 12, "v": "备注",}
      ],
      "config": {
        "merge": {
          "0_0": {
            "r": 0,
            "c": 0,
            "rs": 2,
            "cs": 1
          },
          "0_1": {
            "r": 0,
            "c": 1,
            "rs": 2,
            "cs": 1
          },
          "0_2": {
            "r": 0,
            "c": 2,
            "rs": 2,
            "cs": 1  // 稀释倍数法下合并三个单元格
          },
          "0_3": {
            "r": 0,
            "c": 3,
            "rs": 1,
            "cs": 3  // 稀释倍数法下合并三个单元格
          },
          "0_6": {
            "r": 0,
            "c": 6,
            "rs": 1,
            "cs": 3  // 铂钴比色法下合并四个单元格
          },
          "0_9": {
            "r": 0,
            "c": 9,
            "rs": 2,
            "cs": 1
          },
          "0_10": {
            "r": 0,
            "c": 10,
            "rs": 2,
            "cs": 1
          },
          "0_11": {
            "r": 0,
            "c": 11,
            "rs": 2,
            "cs": 1
          },
          "0_12": {
            "r": 0,
            "c": 12,
            "rs": 2,
            "cs": 1
          },
        }, // 合并单元格
        "columnlen": { // 设置列宽
          "0": 130, // 第一列宽度 150px
          "1": 130, // 第二列宽度 120px
          "2": 130, // 第三列宽度 180px
          "3": 130, // 第四列宽度 100px
          "4": 100, // 第五列宽度 200px
          "5": 100,  // 第六列宽度 150px
          "6": 100,  // 第六列宽度 150px
          "7": 130,  // 第六列宽度 150px
          "8": 130,  // 第六列宽度 150px
          "9": 100,  // 第六列宽度 150px
        }, // 表格列宽
      },
    }
  ],
  showinfobar: false, // 隐藏信息栏
  showtoolbar: true, // 隐藏工具栏
};
const tableOption = ref([
  {table: '仪器名称', id: 1,}
])
const switchAB = ref(true)
const sheetData = ref('')
const jsonData = ref(null)
// 在组件挂载后初始化 Luckysheet
onMounted(() => {
  // 初始化表格
  luckysheet.create(options);
//   获取表单信息
  getWaterCapacity()
  // 获取信息
  getMethod()
//   获取仪器信息
  getDevicList()
});


// 获取信息(也要粘贴)
const getMethod = () => {
  waterForm.value.task_name = analyseStatusPage.waterForm.task_number //任务名称
  waterForm.value.method = analyseStatusPage.waterForm.tableItem.test_method
      ? analyseStatusPage.waterForm.tableItem.test_method
      : analyseStatusPage.waterForm.tableItem.test_method_number;//分析方法
  waterForm.value.category_id = analyseStatusPage.waterForm.tableItem.sample_category // 样品类别
  checkTime.value = analyseStatusPage.waterForm.tableItemList.submit_dates
}


const handleAddWaterPh = () => {
  sheetData.value = luckysheet.getLuckysheetfile();
  options.data = sheetData.value; // 将字符串解析为 JSON
  const data = options.data[0].data.map(row => {
    return row
        .map(cell => {
          return cell ? {
            field: cell.m || "默认字段",
            value: cell.v || null
          } : null;
        })
        .filter(cell => cell !== null); // 删除 null 值
  });
  // 调用函数
  processedData.value = filterValidSampleAdatas(processData(data));
  cdatas.value = filterValidSamples(transformData(processedData.value))
  if (waterForm.value.check_status !== undefined) {
    delete waterForm.value.check_status
    delete waterForm.value.reviewer_id
  }
  //   调接口拿数据
  AnalyesAPI.addWaterCapacity({
    ...waterForm.value,
    record_sn: record_sn,
    // record_sn: 48,
    // id: analyseStatusPage.waterForm.id,
    task_id: analyseStatusPage.waterForm.taskId,
    configs: sheetData.value,
    add_form_id: analyseStatusPage.waterForm.add_form_id,
    adatas: processedData.value,
    cdatas: cdatas.value,
  }).then(data => {
    console.log('调接口拿数据', data)
    ElMessage.success('保存成功！')
    switchAdd.value = false
  })
};

// 获取——获取 水质容量A   工作表
const getWaterCapacity = () => {
  let josn = {
    add_form_id: analyseStatusPage.waterForm.add_form_id,
    task_id: analyseStatusPage.waterForm.taskId,
    // id: 7,
    record_sn: record_sn,
    // record_sn: 49,
  }
  AnalyesAPI.getAnalyseACapacity(josn).then(data => {
    console.log('获取水质容量 A单', data)
    if (!Array.isArray(data) || data.length !== 0) {
      waterForm.value = data;
      sheetData.value = data.configs;
      options.data = sheetData.value;
      luckysheet.create(options);
      processedData.value = data.adatas;

      // 处理 adata 到 pdf
      tableHeaders.value = splitDataIntoPages(data.adatas, 15);
      console.log(tableHeaders.value)
    } else {
      waterForm.value.hz_device = {
        hz_device_name: [],
        hz_device_model: [],
        hz_device_number: [],
      }
      waterForm.value.tp_device = {
        tp_device_name: [],
        tp_device_model: [],
        tp_device_number: [],
      }
    }
  })
}


// 用于获取最新的表格数据
const getUpdatedData = () => {
  checkDialogVisible.value = true
};
const handleCheckClose = () => {
  checkDialogVisible.value = false
}


// 上传文件
const loadExcel = (evt) => {
  const files = evt.target.files
  console.log(files)
  if (files == null || files.length == 0) {
    alert('No files wait for import')
    return
  }
  let name = files[0].name
  let suffixArr = name.split('.'),
      suffix = suffixArr[suffixArr.length - 1]
  if (suffix != 'xlsx') {
    alert('Currently only supports the import of xlsx files')
    return
  }
  LuckyExcel.transformExcelToLucky(files[0], function (exportJson, luckysheetfile) {
    if (exportJson.sheets == null || exportJson.sheets.length == 0) {
      alert('Failed to read the content of the excel file, currently does not support xls files!')
      return
    }
    console.log('exportJson', exportJson.sheets)
    jsonData.value = exportJson

    luckysheet.destroy()
    luckysheet.create({
      container: 'luckysheet', //luckysheet is the container id
      showinfobar: false,
      data: exportJson.sheets,
      title: exportJson.info.name,
      userInfo: exportJson.info.name.creator
    })
  })
}

// 更新avgValues的函数
const updateAvgValues = (index) => {
  if (index === 1) {
    waterForm.value.pxycd[0].px_pjz = calcAverage(0, 1); // 更新第0个索引的平均值
    waterForm.value.pxycd[0].px_xd = calcDiff(0, 1); // 更新第0个索引的平均值
  } else if (index === 3) {
    waterForm.value.pxycd[2].px_pjz = calcAverage(2, 3); // 更新第2个索引的平均值
    waterForm.value.pxycd[2].px_xd = calcDiff(2, 3); // 更新第2个索引的平均值
  }
};

// 计算平均值
function calcAverage(index1, index2) {
  const ph1 = parseFloat(waterForm.value.pxycd[index1]?.px_cdz) || 0;
  const ph2 = parseFloat(waterForm.value.pxycd[index2]?.px_cdz) || 0;
  return ((ph1 + ph2) / 2).toFixed(2);
}

// 计算差值
function calcDiff(index1, index2) {
  const ph1 = parseFloat(waterForm.value.pxycd[index1]?.px_cdz) || 0;
  const ph2 = parseFloat(waterForm.value.pxycd[index2]?.px_cdz) || 0;
  return `${Math.abs((ph1 - ph2) / (ph1 + ph2) * 100).toFixed(2)}`;
}


// 打开分析仪器
const handleOpen = () => {
  assignedDialogVisible.value = true
}

const handleClose = () => {
  assignedDialogVisible.value = false
}

// 打开分析仪器
const handleSpOpen = () => {
  spDialogVisible.value = true
}

const handleSpClose = () => {
  spDialogVisible.value = false
}


// 获取仪器接口
const getDevicList = () => {
  CommonAPI.getdevice().then(res => {
    selectedUsers.value = res
  })
}


const fetchSearchResults = (query) => {
  if (query === '') return
  CommonAPI.getdevice({device_name: query}).then(data => {
    selectedUsers.value = data
  })
}

// 添加表格
const handleSureSample = () => {
  const selectedDevices = selectedUsers.value.filter(device => addSampleForm.value.device_name.includes(device.id));
  waterForm.value.hz_device.hz_device_name = selectedDevices.map(device => device.device_name);
  waterForm.value.hz_device.hz_device_model = selectedDevices.map(device => device.device_model);
  waterForm.value.hz_device.hz_device_number = selectedDevices.map(device => device.device_number);
  assignedDialogVisible.value = false
}


// 添加表格
const handleSpSureSample = () => {
  const selectedDevices = selectedUsers.value.filter(device => addTpSampleForm.value.device_name.includes(device.id));
  waterForm.value.tp_device.tp_device_name = selectedDevices.map(device => device.device_name);
  waterForm.value.tp_device.tp_device_model = selectedDevices.map(device => device.device_model);
  waterForm.value.tp_device.tp_device_number = selectedDevices.map(device => device.device_number);
  spDialogVisible.value = false
}

const handleDelete = (index) => {
  waterForm.value.hz_device.hz_device_name.splice(index, 1);
  waterForm.value.hz_device.hz_device_model.splice(index, 1);
  waterForm.value.hz_device.hz_device_number.splice(index, 1);
}

const handleSpDelete = (index) => {
  waterForm.value.tp_device.tp_device_name.splice(index, 1);
  waterForm.value.tp_device.tp_device_model.splice(index, 1);
  waterForm.value.tp_device.tp_device_number.splice(index, 1);
}

const handleSelectChange = () => {
  sheetData.value = luckysheet.getLuckysheetfile();
  options.data = sheetData.value; // 将字符串解析为 JSON
  const data = options.data[0].data.map(row => {
    return row
        .map(cell => {
          return cell ? {
            field: cell.m || "默认字段",
            value: cell.v || null
          } : null;
        })
        .filter(cell => cell !== null); // 删除 null 值
  });
  ypbhOptions.value = filterParallelSamples(filterValidSampleAdatas(processTableData(data)));
}

function handleChange(item) {
  // 根据选中的样品编号，找到对应的 finalResult
  const selectedOption = ypbhOptions.value.find(
      option => option.sampleNumber === item.px_pxybh
  );

  // 如果找到了对应的选项，则将 finalResult 赋值给 px_phz
  if (selectedOption) {
    item.px_cdz = selectedOption.finalResult;
  }
}
</script>

<template>
  <div class="card">
    <div v-show="!showTargetPage">
      <el-card class="box-card">
        <h1 style="text-align: center">水质 重量法分析原始记录</h1>
        <div>SXLPHJ/JL/CX-22-48</div>
        <table class="table">
          <tr style="background-color: #f2f2f2">
            <td>任务编号</td>
            <td>
              <el-input style="width: 100%;border: 1px solid transparent" placeholder="请输入"
                        v-model="waterForm.task_name"/>
            </td>
            <td>分析项目</td>
            <td>
              <el-input style="width: 100%;border: 1px solid transparent" placeholder="请输入"
                        v-model="waterForm.fxxm"/>
            </td>
            <td>采样日期</td>
            <td>
              <el-input style="width: 100%;border: 1px solid transparent" placeholder="请输入"
                        v-model="waterForm.sampling_time"/>
            </td>
            <td>分析日期</td>
            <td>
              <el-input style="width: 100%;border: 1px solid transparent" placeholder="请输入"
                        v-model="waterForm.anal_time"/>
            </td>
          </tr>
          <tr>
            <td>分析方法</td>
            <td colspan="5">
              <el-input style="width: 100%;border: 1px solid transparent" placeholder="请输入"
                        v-model="waterForm.method"/>
            </td>
            <td>样品类别</td>
            <td>
              <el-input style="width: 100%;border: 1px solid transparent" placeholder="请输入"
                        v-model="waterForm.category_id"/>
            </td>
          </tr>
          <tr style="background-color: #f2f2f2">
            <td>恒重仪器</td>
            <td @click="handleOpen">
              <div v-for="(item,index) in  waterForm.hz_device.hz_device_name" :key="index"
                   style="display: flex;align-items: center;justify-content: space-between">
                <span>{{ item }}</span>
                <span style="cursor: pointer">
                  <el-icon size="16" @click.stop="handleDelete(index)">
                          <Coffee/>
                        </el-icon>
                </span>
              </div>
            </td>
            <td>仪器型号</td>
            <td>
              <div v-for="(item,index) in waterForm.hz_device.hz_device_model" :key="index">{{ item }}</div>
            </td>
            <td>仪器编号</td>
            <td>
              <div v-for="(item,index) in waterForm.hz_device.hz_device_number" :key="index">{{ item }}</div>
            </td>
            <td>环境温度</td>
            <td>
              <el-input style="width: 100%;border: 1px solid transparent" placeholder="请输入"
                        v-model="waterForm.temperature">
                <template #append>
                  <span style="background-color: transparent;color: black">℃</span>
                </template>
              </el-input>
            </td>
          </tr>
          <tr>
            <td>天平级别</td>
            <td @click="handleSpOpen">
              <div v-for="(item,index) in  waterForm.tp_device.tp_device_name" :key="index"
                   style="display: flex;align-items: center;justify-content: space-between">
                <span>{{ item }}</span>
                <span style="cursor: pointer">
                  <el-icon size="16" @click.stop="handleSpDelete(index)">
                          <Coffee/>
                        </el-icon>
                </span>
              </div>

            </td>
            <td>天平型号</td>
            <td>
              <div v-for="(item,index) in waterForm.tp_device.tp_device_model" :key="index">{{ item }}</div>
            </td>
            <td>天平编号</td>
            <td>
              <div v-for="(item,index) in waterForm.tp_device.tp_device_number" :key="index">{{ item }}</div>
            </td>
            <td>环境湿度</td>
            <td>
              <el-input style="width: 100%;border: 1px solid transparent" placeholder="请输入"
                        v-model="waterForm.humidity">
                <template #append>
                  <span style="background-color: transparent;color: black">%RH</span>
                </template>
              </el-input>
            </td>
          </tr>
          <tr>
            <td>计算公式</td>
            <td colspan="7">
              <el-input style="width: 100%;border: 1px solid transparent" placeholder="请输入"
                        v-model="waterForm.js_formula"/>
            </td>
          </tr>
          <tr>
            <td>样品处理</td>
            <td colspan="7">
              <el-input style="width: 100%;border: 1px solid transparent" placeholder="请输入"
                        v-model="waterForm.process"/>
            </td>
          </tr>
        </table>
        <!--      <input id="uploadBtn" type="file" @change="loadExcel"/>-->
        <div id="luckysheet" style="width:100%;height:500px;"></div>
        <table class="table">
          <tr>
            <td colspan="8" style="text-align: center">平行样测定</td>
          </tr>
          <tr>
            <td>平行样编号</td>
            <td>
              <div style="display: flex;align-items: center;">
                测定值 (
                <el-input style="width: 50%;border: 1px solid transparent" placeholder="请输入"
                          v-model="waterForm.unit.px_cdz"/>
                )
              </div>
            </td>
            <td>

              <div style="display: flex;align-items: center;">
                平均值 (
                <el-input style="width: 50%;border: 1px solid transparent" placeholder="请输入"
                          v-model="waterForm.unit.px_pjz"/>
                )
              </div>
            </td>
            <td>
              <div style="display: flex;align-items: center;">
                相对 (
                <el-input style="width: 50%;border: 1px solid transparent" placeholder="请输入"
                          v-model="waterForm.unit.px_xd"/>
                )（%）
              </div>
            </td>
            <td>
              质控要求（%）
            </td>
            <td>
              是否合格（%）
            </td>
          </tr>
          <tr v-for="(item,index) in waterForm.pxycd" :key="index">
            <td style="width: 200px;">
              <el-select v-model="item.px_pxybh" placeholder="请选择" style="width: 100%; border: 1px solid transparent"
                         filterable
                         allow-create
                         default-first-option
                         @focus="handleSelectChange" @change="handleChange(item)">
                <el-option
                    v-for="(option, index) in ypbhOptions"
                    :key="index"
                    :label="option.sampleNumber"
                    :value="option.sampleNumber">
                </el-option>
              </el-select>
              <!--              <el-input style="width: 100%;border: 1px solid transparent" placeholder="请输入"-->
              <!--                        v-model="item.px_pxybh"/>-->
            </td>
            <td>
              <el-input style="width: 100%;border: 1px solid transparent" placeholder="请输入"
                        v-model="item.px_cdz" @blur="updateAvgValues(index)"/>
            </td>
            <td v-if="index === 0 || index === 2" rowspan="2">
              <el-input style="width: 100%;border: 1px solid transparent" placeholder="请输入"
                        v-model="item.px_pjz"/>
            </td>
            <td v-if="index === 0 || index === 2" rowspan="2">
              <el-input style="width: 100%;border: 1px solid transparent" placeholder="请输入"
                        v-model="item.px_xd"/>
            </td>
            <td v-if="index === 0 || index === 2" rowspan="2">
              <el-input style="width: 100%;border: 1px solid transparent" placeholder="请输入"
                        v-model="item.px_zkyq"/>
            </td>
            <td v-if="index === 0 || index === 2" rowspan="2">
              <el-input style="width: 100%;border: 1px solid transparent" placeholder="请输入"
                        v-model="item.px_sfhg"/>
            </td>
          </tr>
          <tr>
            <td>备注</td>
            <td colspan="5">
              <el-input style="width: 100%;border: 1px solid transparent" placeholder="请输入"
                        v-model="waterForm.notes"/>
            </td>
          </tr>
        </table>
      </el-card>
    </div>

    <!--    pdf组件-->
    <div v-show="showTargetPage">
      <indexPdf :waterForm="waterForm" :tableHeaders="tableHeaders" :tabler="tabler"></indexPdf>
    </div>

    <!--    底部公共按钮-->
    <div>
      <Index :water-form="waterForm" :handle-add-water-ph="handleAddWaterPh"
             :get-water-capacity="getWaterCapacity" :switch-add="switchAdd"></Index>
    </div>

    <!--    恒重仪器-->
    <el-dialog title="添加仪器" v-model="assignedDialogVisible" width="30%" center :before-close="handleClose">
      <el-form ref="form" :model="addSampleForm" label-width="90px">
        <el-form-item label="仪器名称：">

          <el-select v-model="addSampleForm.device_name" placeholder="请选择" filterable remote multiple
                     :remote-method="fetchSearchResults">
            <el-option
                v-for="(label, value) in selectedUsers"
                :key="value"
                :label="`${label.device_name} (${label.device_number})`"
                :value="label.id">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer" style="display: flex;justify-content: center">
        <el-button @click="handleClose" style="width: 50%">取 消</el-button>
        <el-button type="primary" style="width: 50%" @click="handleSureSample">确 定</el-button>
      </span>
    </el-dialog>

    <!--    水平仪器-->
    <el-dialog title="添加仪器" v-model="spDialogVisible" width="30%" center :before-close="handleSpClose">
      <el-form ref="form" :model="addTpSampleForm" label-width="90px">
        <el-form-item label="仪器名称：">

          <el-select v-model="addTpSampleForm.device_name" placeholder="请选择" filterable remote multiple
                     :remote-method="fetchSearchResults">
            <el-option
                v-for="(label, value) in selectedUsers"
                :key="value"
                :label="`${label.device_name} (${label.device_number})`"
                :value="label.id">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer" style="display: flex;justify-content: center">
        <el-button @click="handleSpClose" style="width: 50%">取 消</el-button>
        <el-button type="primary" style="width: 50%" @click="handleSpSureSample">确 定</el-button>
      </span>
    </el-dialog>
  </div>

</template>

<style scoped>
.card {
  padding: 20px 25px;
}

.table {
  width: 100%;
  border-collapse: collapse; /* 表格边框合并 */
  text-align: left; /* 默认左对齐 */
  font-size: 14px; /* 字体大小 */
  color: #606266; /* 默认字体颜色 */
  margin-bottom: 20px;
}

.table th,
.table td {
  border: 1px solid #c2bfbf; /* 表格单元格边框颜色 */
  padding: 12px; /* 单元格内边距 */
}

.table th {
  background: #f5f7fa; /* 表头背景色 */
  font-weight: 600; /* 表头字体加粗 */
  color: #303133; /* 表头字体颜色 */
  text-align: center; /* 表头居中 */
}


.table-td {
  display: flex;
}

::v-deep .el-input__wrapper {
  background-color: transparent;
  box-shadow: none;
  flex-direction: row-reverse;
}

::v-deep .el-select__wrapper {
  background-color: transparent;
  box-shadow: none;
}

::v-deep .el-input-group__append {
  background-color: transparent;
  box-shadow: none;
}
</style>
